package org.game.module.fight.handler;

import org.cfg.DungeonLevelCfg;
import org.cfg.DungeonLevelGroupCfg;
import org.cfg.MainLineCfg;
import org.cfg.cache.MainLineCfgCache;
import org.error.GameErrorCode;
import org.game.constant.DungeonConstant;
import org.game.db.bean.DungeonLevel;
import org.game.db.bean.DungeonLevelGroup;
import org.game.db.bean.Player;
import org.game.manager.DungeonManager;
import org.game.module.dungeonbo.DungeonBO;
import org.game.module.fight.AbstractFight;
import org.game.module.fight.dungeom.DungeonCheck;
import org.game.msgBuilder.DungeonMsgBuilder;
import org.game.protobuf.s2c.S2CDungeonMsg.FightOverMsg;
import org.utils.ProtoUnit;

import com.sojoys.artifact.factory.message.IMessage;
import com.sojoys.artifact.manager.MessageManager;
import com.sojoys.artifact.tools.ToolError;

/**
 * @author : DengYing
 * @CreateDate : 2018年8月14日 下午7:28:13
 * @Description ：主线关卡
 */
public class MainDungeonHandler extends DungeonFightHandler {

	public MainDungeonHandler(Player player, DungeonLevelCfg cfg, DungeonLevel dungeonLevel,DungeonLevelGroupCfg dungeonLevelGroupCfg) {
		super(player, cfg, dungeonLevel, dungeonLevelGroupCfg);
	}

	@Override
	public boolean startCheck(AbstractFight fight) {
		DungeonCheck.checkPreLevel(player, cfg);
		DungeonCheck.checkCost(player, cfg);
		DungeonCheck.checkFightCount(cfg, dungeonLevel);
		return true;
	}

	@Override
	public void fightWin(AbstractFight fight) {
		// 主线副本无星级
		dungeonLevel.setStar(0);
		dungeonLevel.setWin(true);
		dungeonLevel.setFightCount(dungeonLevel.getFightCount() + 1);
		dungeonLevel.update();

		MainLineCfg mainLineCfg = MainLineCfgCache.me().getByTypeArgument(DungeonConstant.MAIN_LINE_TYPE_CHAPTER,dungeonLevel.getDungeonLevelProxy().getCfg().getId() + "");
		if (mainLineCfg != null) {
			DungeonLevelGroup group = updateGroupStoryProgress(player, mainLineCfg);
			player.getPlayerProxy().sendMsg(DungeonBO.promoteStory, DungeonMsgBuilder.getProgressMsg(group));
		}
		pushRewards(fight);
		dealHelpFighter(fight,player);
	}

	public static byte[] promoteStory(Player player, int dungeonType, int cid) {
        //主线配置校验
        MainLineCfg mainLineCfg = MainLineCfgCache.me().getById(cid);
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, mainLineCfg == null);
        DungeonLevelGroup group = updateGroupStoryProgress(player, mainLineCfg);
        return ProtoUnit.toByte(DungeonMsgBuilder.getProgressMsg(group));
    }

	private static DungeonLevelGroup updateGroupStoryProgress(Player player, MainLineCfg cfg) {
		DungeonLevelGroup group = DungeonManager.getOrInitDungeonLevelGroup(player, cfg.getLevelGroupId());
		group.setLastMainLine(cfg.getId());
		if (cfg.getId() > group.getMaxMainLine()){
		    group.setMaxMainLine(cfg.getId());
		}
		group.update();
		return group;
  }
}
